package com.studentgrowth.service.auth.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.studentgrowth.mapper.UserMapper;
import com.studentgrowth.model.auth.User;
import com.studentgrowth.service.auth.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User register(String username, String password) {
        // 检查用户名是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        if (userMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        // 保存用户
        userMapper.insert(user);
        return user;
    }

    @Override
    public User login(String username, String password) {
        logger.info("尝试登录，用户名: {}", username);

        // 查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
            logger.warn("登录失败，用户不存在: {}", username);
            return null;
        }

        if (passwordEncoder.matches(password, user.getPassword())) {
            logger.info("登录成功，用户名: {}", username);
            return user;
        } else {
            logger.warn("登录失败，密码错误，用户名: {}", username);
            return null;
        }
    }

    @Override
    public User getById(Long id) {
        return userMapper.selectById(id);
    }
} 